package com.rainng.coursesystem.service;

import com.rainng.coursesystem.model.CourseResourceItem;
import com.rainng.coursesystem.model.ExamItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
public class ClassroomExamService {

    @Autowired
    private com.rainng.coursesystem.repository.ExamRepository ExamRepository;

    @Autowired
    private com.rainng.coursesystem.repository.SubmitHomeworkRepository SubmitHomeworkRepository;

    @Autowired
    private com.rainng.coursesystem.repository.StudentRepository StudentRepository;

    @Value("D:\\1")
    private String uploadDir;




    // 上传文件并自动添加到收藏夹
    public String TeacherArrangeExam(String roomNumber, Long courseId, Date examTime, String isRandom) throws Exception {
        List<ExamItem> examItems = new ArrayList<>();
        List<Long> studentIds = StudentRepository.findStudentByCourseId(courseId);
        int size = studentIds.size();

        // 创建一个包含序列号的列表，并打乱顺序
        List<Integer> sequenceList = new ArrayList<>();
        for (int i = 1; i <= size; i++) {
            sequenceList.add(i);
        }
        if("yes".equals(isRandom))
        {
            Collections.shuffle(sequenceList);
        }

        // 为每个学生创建一个ExamItem对象，并添加到列表中
        for (int i = 0; i < size; i++) {
            ExamItem item = new ExamItem(); // 在循环内部创建新的ExamItem对象
            item.setRoomNumber(roomNumber);
            item.setExamTime(examTime);
            item.setCourseId(courseId);
            item.setStudentId(studentIds.get(i));
            item.setSetNumber(sequenceList.get(i));
            examItems.add(item); // 将创建的ExamItem对象添加到列表中
        }

        // 批量保存所有ExamItem对象到数据库
        ExamRepository.saveAll(examItems);

        return "exam uploaded successfully!";
    }

    public List<ExamItem> listExam(long studentId) { //教师端通过作业id查看所有作业
        return ExamRepository.findAllByStudentId(studentId);
    }

    public List<ExamItem> viewExam(long courseId) {return ExamRepository.findAllByCourseId(courseId);
    }

    public List<ExamItem> listExamByCourseId(Long studentId, Long courseId) {
        return ExamRepository.findAllByCourseIdAndStudentId(courseId,studentId);
    }

    public void removeExam(Date examTime, String roomNumber) {
        List<ExamItem> examItems = ExamRepository.findAllByExamTimeAndRoomNumber(examTime, roomNumber);

        if (!examItems.isEmpty()) {
            // 如果列表不为空，删除所有匹配的 ExamItem
            ExamRepository.deleteAll(examItems);
        }
    }
}
